package vn.csp.gameportal;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import vn.csp.gameportal.R;
import vn.csp.util.ThongSo;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;

import com.actionbarsherlock.app.ActionBar;

public class GameDownload extends Activity implements ViewFactory{
	// Danh sách hình ảnh game cho thông tin game
		Integer pics[] = { R.drawable.icons,R.drawable.icons, R.drawable.icons, R.drawable.icons,
				R.drawable.icons };
		
		ImageButton imgBtn_taigame; 
	    private ProgressDialog pDialog;
		private String id_path;

		private ImageSwitcher iSwitcher;

		private ImageView icon;

		private TextView ten_game;

		private TextView chu_de;

		private TextView luot_xem;

		private TextView luot_tai;

		private ImageSwitcher ImageSwitcher01;

		private TextView mo_ta_game;

		private ImageView nut_tai;

		private ThongTinGame gameHayNhat;
		
	    // Progress dialog type (0 - for Horizontal progress bar)
	    public static final int progress_bar_type = 0; 
	    private static String file_url = "";
	   
	    public void thamChieuUI(){
	    	icon = (ImageView)findViewById(R.id.icon);
	    	ten_game = (TextView)findViewById(R.id.ten_game);
	    	chu_de = (TextView)findViewById(R.id.chu_de);
	    	luot_xem = (TextView)findViewById(R.id.luot_xem);
	    	luot_tai = (TextView)findViewById(R.id.luot_tai);
	    	ImageSwitcher01 = (ImageSwitcher)findViewById(R.id.ImageSwitcher01);
	    	mo_ta_game = (TextView)findViewById(R.id.mo_ta_game);
	    	nut_tai = (ImageView)findViewById(R.id.nut_tai);
	    }
	    @Override
		  public boolean onOptionsItemSelected(MenuItem item) {
		    switch (item.getItemId()) {
		    /**
		     * Trở về activity trước
		     */
		    case android.R.id.home:
		    	finish();
		        return true;
		    }
		    return true;
		  }
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_gamedownload);
			thamChieuUI();
			
			android.app.ActionBar actionBar = getActionBar();
			actionBar.setTitle(Html.fromHtml("<font color='#ffffff'>Game Potal</font>"));
			actionBar.setSubtitle(Html.fromHtml("<font color='#ffffff'>Tất cả</font>"));
			//hiển thị nút back trên giao diện
	        actionBar.setDisplayHomeAsUpEnabled(true); 
	        actionBar.setDisplayShowTitleEnabled(true);
	        
			// Lấy đối tượng ThongTinGameHayNhat
			gameHayNhat = (ThongTinGame) getIntent().getExtras().getSerializable("ThongTinGameHayNhat");
			
			//icon
			icon.setImageResource(R.drawable.icons);
			ten_game.setText(gameHayNhat.getTTG_TEN_GAME());
			chu_de.setText("Thể loại: "+gameHayNhat.getTLG_TEN_THE_LOAI());
			luot_xem.setText("Lượt xem: "+gameHayNhat.getTTG_LUOT_XEM());
			
			/**-----ImageSwitcher01 ----- */
			ImageSwitcher01.setFactory(this);
			ImageSwitcher01.setInAnimation(AnimationUtils.loadAnimation(this,
					android.R.anim.fade_in));
			ImageSwitcher01.setOutAnimation(AnimationUtils.loadAnimation(this,
					android.R.anim.fade_out));
			Gallery gallery = (Gallery) findViewById(R.id.Gallery01);
			gallery.setAdapter(new ImageAdapter(this));
			gallery.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
					//Load hinh ra gallery
//					iSwitcher.setImageResource(pics[arg2]);
				}
			});
			/**-----ImageSwitcher01 ----- */
			
			luot_tai.setText(gameHayNhat.getTTG_LUOT_TAI());
			
			String noi_dung_mo_ta = gameHayNhat.getTTG_NOI_DUNG_MO_TA();
//			Toast.makeText(getApplicationContext(), noi_dung_mo_ta.length()+"-", 1000).show();
			
			
			if(noi_dung_mo_ta.length()==0){
				mo_ta_game.setText("Đang cập nhật nội dung mô tả game");
			}else{
				mo_ta_game.setText(Html.fromHtml(noi_dung_mo_ta));
			}
			
			/** --- Xử lí nút download */
			nut_tai.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Tải game về máy
					ThongSo ts = new ThongSo(); 
					String game_path = ts.URL_DOWN+gameHayNhat.getTTG_DUONG_DAN(); // đường dẫn game
//					Toast.makeText(getApplicationContext(), game_path, 1000).show();
					new DownloadFileFromURL().execute(game_path);
				}
			});
//			id_path = getIntent().getExtras().getString("id_path");
//			if(id_path!=null){
//			layDuLieu();
			//new DownloadFileFromURL().execute(file_url);
			
//				imgBtn_taigame = (ImageButton) findViewById(R.id.imgBtn_taigame);
//				imgBtn_taigame.setOnClickListener(new OnClickListener() {
//					
//					@Override
//					public void onClick(View v) {
//						// TODO Tải game về máy
//						ThongSo ts = new ThongSo(); 
//						String game_path = ts.URL_DOWN+id_path; // đường dẫn game
//						new DownloadFileFromURL().execute(game_path);
//					}
//				});
//				
				
				
			}
//		Handler myHandler = new Handler() {
//			public void handleMessage (Message m) {
//				String thong_diep_loi = m.getData().getString("thong_diep_loi");
//				if(thong_diep_loi!=null){
//					Toast.makeText(getApplicationContext(),thong_diep_loi, 1000).show();
//				}else{
//					String x = file_url;
//					new DownloadFileFromURL().execute(id_path);
////					if (!danh_sach_game_tai_nhieu.isEmpty()){
////						ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_list_item_1, danh_sach_game_tai_nhieu);
////						Toast.makeText(getActivity().getApplicationContext(),"Tải dữ liệu thành công", 1000).show();
////						setListAdapter(adapter);
////					}
//				}
//			}
//		};
	//	
//	    public void layDuLieu() {
//			new Thread(){
//				@Override
//				public void run() {
//					// TODO Auto-generated method stub
//					JSONParser jsonParser = new JSONParser();
//			        try {
//			        	ThongSo thongSo = new ThongSo();
//			        	JSONObject jsonObject = jsonParser.getJSONFromUrl(thongSo.URL,thongSo.CODE_PHP,ThongSo.YEU_CAU.GAME_DUONG_DAN.toString(),id_game);
//			        	
//			        	JSONArray androidArray = jsonObject.getJSONArray("JSONResponse");
//			        	androidArray.getJSONObject(0);
//			        	JSONObject jsonObject2 =androidArray.getJSONObject(0);
//			        	file_url = jsonObject2.getString("DD_GAME");
//			        	Message m = myHandler.obtainMessage();
//						myHandler.sendMessage(m);
//						
//					} catch (Exception e) {
//						// TODO: handle exception
//						android.util.Log.i("TAG",e.toString());
//						Message m = myHandler.obtainMessage();
//						Bundle b = new Bundle();
//						b.putString("thong_diep_loi", "Vui lòng kiểm tra kết nối");
//						m.setData(b);
//						myHandler.sendMessage(m);
//					}
//					
//				}
//			}.start();
//		}
		/**
		 * Showing Dialog
		 * */
		@Override
		protected Dialog onCreateDialog(int id) {
		    switch (id) {
		    case progress_bar_type:
		        pDialog = new ProgressDialog(this);
		        pDialog.setMessage("Đang tải game,..");
		        pDialog.setIndeterminate(false);
		        pDialog.setMax(100);
		        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		        pDialog.setCancelable(false); // cho phep ngat ngang tien trinh
		        pDialog.show();
		        return pDialog;
		    default:
		        return null;
		    }
		}
		class DownloadFileFromURL extends AsyncTask<String, String, String>{

			/**
		     * Before starting background thread
		     * Show Progress Bar Dialog
		     * */
		    @Override
		    protected void onPreExecute() {
		        super.onPreExecute();
		        showDialog(progress_bar_type);
		    }
			
			@Override
			protected String doInBackground(String... f_url) {
				// TODO Auto-generated method stub
				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); // không cho xoay màn hình
				int count;
		        try {
		            URL url = new URL(f_url[0]);
		            URLConnection conection = url.openConnection();
		            conection.setConnectTimeout(5000);
		            conection.connect();
		            // getting file length
		            int lenghtOfFile = conection.getContentLength();
		            // input stream to read file - with 8k buffer
		            InputStream input = new BufferedInputStream(url.openStream(), 8192);
		            // Output stream to write file
		             
		           // OutputStream output = new FileOutputStream("/sdcard/"+file_url.split("/")[4]+".apk");
		            String x = "/sdcard/"+gameHayNhat.getTTG_DUONG_DAN();
		            
		            OutputStream output = new FileOutputStream("/sdcard/"+gameHayNhat.getTTG_DUONG_DAN());//+".apk");
		            byte data[] = new byte[1024];
		            long total = 0;
		            while ((count = input.read(data)) != -1) {
		                total += count;
		                // publishing the progress....
		                // After this onProgressUpdate will be called
		                publishProgress(""+(int)((total*100)/lenghtOfFile));
		                // writing data to file
		                output.write(data, 0, count);
		            }
		            // flushing output
		            output.flush();
		            // closing streams
		            output.close();
		            input.close();
		 
		        } catch (Exception e) {
		        	thongBao("Có lỗi tại server");
		            Log.e("Error: ", e.getMessage());
		            pDialog.setCancelable(true);// có lỗi trong quá trình download tự đóng của sổ
			        dismissDialog(progress_bar_type);
		        }
		 
		        return null;
			}
			 /**
		     * Updating progress bar
		     * */
		    protected void onProgressUpdate(String... progress) {
		        // setting progress percentage	
		        pDialog.setProgress(Integer.parseInt(progress[0]));
		   }
		 
		    /**
		     * Sau khi download thành công
		     * Dismiss the progress dialog
		     * **/
		    @Override
		    protected void onPostExecute(String file_url) {
		    	/**
		    	 * sau khi download cho phep tat Dialog
		    	 */
			    	pDialog.setCancelable(true);
			        dismissDialog(progress_bar_type);
			        String imagePath = Environment.getExternalStorageDirectory().toString() + "/"+gameHayNhat.getTTG_DUONG_DAN();//+".apk";
			        openFile(imagePath);
			        pDialog.setCancelable(false);// sau khi download cho phep tat
		    }
		    
		    protected void openFile(String fileName) {
		        Intent install = new Intent(Intent.ACTION_VIEW);
		        install.setDataAndType(Uri.fromFile(new File(fileName)),
		                "application/vnd.android.package-archive");
		        startActivity(install);
		    }
		}
		/**-----ImageSwitcher01 ----- */
		public class ImageAdapter extends BaseAdapter {

			private Context ctx;

			public ImageAdapter(Context c) {
				ctx = c; 
			}

			@Override
			public int getCount() {

				return pics.length;
			}

			@Override
			public Object getItem(int arg0) {

				return arg0;
			}

			@Override
			public long getItemId(int arg0) {

				return arg0;
			}

			@Override
			public View getView(int arg0, View arg1, ViewGroup arg2) {

				ImageView iView = new ImageView(ctx);
				iView.setImageResource(pics[arg0]);
				iView.setScaleType(ImageView.ScaleType.FIT_XY);
				iView.setLayoutParams(new Gallery.LayoutParams(150, 150));
				return iView;
			}

		}
		/**-----ImageSwitcher01 ----- */
		@Override
		public View makeView() {
			ImageView iView = new ImageView(this);
			iView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			iView.setLayoutParams(new 
					ImageSwitcher.LayoutParams(
							LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
			iView.setBackgroundColor(0xFF000000);
			return iView;
		}
		/**-----ImageSwitcher01 ----- */
		/**
	     * 
	     * @param noiDung : thông điệp cần hiển thị.
	     * Dùng trong tình huống muốn hiện các thông báo
	     */
	    public void thongBao(String noiDung){
	    	Toast.makeText(getApplicationContext(), noiDung, Toast.LENGTH_LONG).show();
	    }
}
